/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CrearFactura.java
 *
 * Created on 13-abr-2009, 10:34:59
 */

package laboratorio;


import gestion.AlbaranFactura;
import gestion.Albaran;
import gestion.Trabajo;
import gestion.Factura;
import clientes.Cliente;
import java.util.*;
import javax.persistence.*;
import javax.swing.JOptionPane;


/**
 *
 * @author Juan Antonio Tirado
 */
public class CrearFactura extends javax.swing.JFrame {
    //ATRIBUTOS
    private Cliente clienteSeleccionado;
    private Query q1,q2,q3,q4,q5,q6;

    private Albaran albaran;
    private Trabajo trabajo;
    private Cliente cliente;

    private Facturas ventanaFacturasOld;
    private List albaranesCliente,facturas,trabajos,albaranes,albaranFactura;

    private ListIterator itAlbaranCliente,itTrabajos,itClientes;

    private int i;
    private float contador;

    /** Creates new form CrearFactura */
    public CrearFactura() {
        
        initComponents();
        Date d=new Date();
        String s=String.valueOf(d.getDate()).concat("-").concat(String.valueOf(d.getMonth()+1)).concat("-").concat(String.valueOf(d.getYear()+1900));
        jTextField1.setText(s);
        jTextField2.setText("");


    }

    CrearFactura(Facturas aThis) {
        ventanaFacturasOld=aThis;
        initComponents();
        Date d=new Date();
        String s=String.valueOf(d.getDate()).concat("-").concat(String.valueOf(d.getMonth()+1)).concat("-").concat(String.valueOf(d.getYear()+1900));
        jTextField1.setText(s);
        jTextField2.setText("");
    }



    private void setAlbaranes(Cliente clienteSeleccionado) {
        for(i=0;i<20;i++){
            jTable2.setValueAt("", i, 0);
            jTable2.setValueAt("", i, 1);
            jTable2.setValueAt("", i, 2);
            jTable2.setValueAt("", i, 3);
        }
        
        q1 = lpdPUEntityManager.createQuery("SELECT a FROM Albaran a,Trabajo t WHERE a.iDtrabajo=t.iDtrabajo AND t.iDcliente="+clienteSeleccionado.getIDcliente());
        albaranesCliente= q1.getResultList();
        i=0;
        contador=0;
        itAlbaranCliente=albaranesCliente.listIterator();
        while(itAlbaranCliente.hasNext()){
            albaran=(Albaran) itAlbaranCliente.next();
            q2 = lpdPUEntityManager.createQuery("SELECT f FROM AlbaranFactura f WHERE f.albaranFacturaPK.iDalbaran="+albaran.getIDalbaran());
            facturas= q2.getResultList();
            if(facturas.isEmpty()){
                imprimeAlbaran(albaran);
            }
        }
        jTextField2.setText(String.valueOf(contador));
    }


    private void imprimeAlbaran(Albaran albaran) {
        jTable2.setValueAt(albaran.getIDalbaran(), i, 0);//id albaran
        jTable2.setValueAt(albaran.getFecha(), i, 1);// fecha
        jTable2.setValueAt(albaran.getTotal(), i, 3);//importe total
        contador=contador+albaran.getTotal();
        q3 = lpdPUEntityManager.createQuery("SELECT t FROM Albaran a,Trabajo t WHERE a.iDtrabajo=t.iDtrabajo AND a.iDalbaran="+albaran.getIDalbaran());
        trabajos= q3.getResultList();
        itTrabajos=trabajos.listIterator();
        if(itTrabajos.hasNext()){
             trabajo=(Trabajo) itTrabajos.next();
             jTable2.setValueAt(trabajo.getPaciente(), i, 2);//paciente
        }
        i++;
    }
   /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        lpdPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("lpdPU").createEntityManager();
        clienteQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT c FROM Cliente c");
        clienteList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clienteQuery.getResultList();
        albaranQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT a FROM Albaran a");
        albaranList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : albaranQuery.getResultList();
        albaranFacturaQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT a FROM AlbaranFactura a");
        albaranFacturaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : albaranFacturaQuery.getResultList();
        facturaQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT f FROM Factura f");
        facturaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : facturaQuery.getResultList();
        facturaQuery1 = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT f FROM Factura f");
        facturaList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : facturaQuery1.getResultList();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(laboratorio.LaboratorioApp.class).getContext().getResourceMap(CrearFactura.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel1.border.titleFont"), resourceMap.getColor("jPanel1.border.titleColor"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setName("jTable1"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, clienteList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${IDcliente}"));
        columnBinding.setColumnName("IDcliente");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nombre}"));
        columnBinding.setColumnName("Nombre");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                SeleccionarCliente(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable1.columnModel.title0")); // NOI18N
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable1.columnModel.title1")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 653, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(53, Short.MAX_VALUE))
        );

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Nº Albaran", "Fecha", "Paciente", "Importe"
            }
        ));
        jTable2.setName("jTable2"); // NOI18N
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable2.columnModel.title0")); // NOI18N
        jTable2.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable2.columnModel.title1")); // NOI18N
        jTable2.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable2.columnModel.title2")); // NOI18N
        jTable2.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTable2.columnModel.title3")); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jTextField1.setText(resourceMap.getString("jTextField1.text")); // NOI18N
        jTextField1.setName("jTextField1"); // NOI18N

        jButton1.setFont(resourceMap.getFont("jButton1.font")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                salir(evt);
            }
        });

        jButton2.setFont(resourceMap.getFont("jButton2.font")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Fac(evt);
            }
        });

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jTextField2.setText(resourceMap.getString("jTextField2.text")); // NOI18N
        jTextField2.setName("jTextField2"); // NOI18N

        jLabel12.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N

        jButton3.setFont(resourceMap.getFont("jButton3.font")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                facturarTodo(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(94, 94, 94)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(62, 62, 62)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 652, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(79, 79, 79)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                                    .addComponent(jLabel1)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(27, 27, 27)
                                .addComponent(jLabel2)
                                .addGap(27, 27, 27)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel12)
                                .addGap(11, 11, 11)))))
                .addContainerGap(23, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(49, 49, 49)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(46, 46, 46)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2))
                            .addComponent(jLabel12)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void salir(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_salir
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_salir

    private void SeleccionarCliente(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SeleccionarCliente
        
        int row=jTable1.getSelectedRow();
        clienteSeleccionado=clienteList.get(row);
        setAlbaranes(clienteSeleccionado);
    }//GEN-LAST:event_SeleccionarCliente

    private void Fac(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Fac
        this.Facturar();
}//GEN-LAST:event_Fac
    
    public void Facturar(){   
        q4 = lpdPUEntityManager.createQuery("SELECT f FROM Factura f");
        facturas= q4.getResultList();
        Factura factura=(Factura) facturas.get(facturas.size()-1);
        Integer iDfactura=factura.getIDfactura()+1;
        Date d=new Date();
        String s=String.valueOf(d.getDate()).concat("-").concat(String.valueOf(d.getMonth()+1)).concat("-").concat(String.valueOf(d.getYear()+1900));
        String fecha=s;
        Integer iDcliente=clienteSeleccionado.getIDcliente();
        float total=contador;
        Boolean cobrado=false;
        Factura f=new Factura(iDfactura,fecha,iDcliente,total,cobrado,0,0);

        lpdPUEntityManager.getTransaction().begin();
      	lpdPUEntityManager.persist(f);
      	lpdPUEntityManager.getTransaction().commit();
        facturaList.add(f);
        facturaList1.add(f);
        itAlbaranCliente=albaranesCliente.listIterator();
        while(itAlbaranCliente.hasNext()){
            albaran=(Albaran) itAlbaranCliente.next();
            AlbaranFactura af=new AlbaranFactura(albaran.getIDalbaran(),f.getIDfactura());
            lpdPUEntityManager.getTransaction().begin();
            lpdPUEntityManager.persist(af);
          	lpdPUEntityManager.getTransaction().commit();
        }
        
        ventanaFacturasOld.setFacturaSelec(f);
        ventanaFacturasOld.setVisible(true);
        this.setVisible(false);}



    private void facturarTodo(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_facturarTodo
        albaranesCliente=new LinkedList();
        itClientes=clienteList.listIterator();
        while (itClientes.hasNext()){
            albaranesCliente.clear();
            clienteSeleccionado=(Cliente) itClientes.next();
            Query q=lpdPUEntityManager.createQuery("SELECT a FROM Albaran a, Trabajo t WHERE a.iDtrabajo=t.iDtrabajo AND t.iDcliente="+clienteSeleccionado.getIDcliente());
            albaranes=q.getResultList();
            Iterator italb=albaranes.iterator();
            while(italb.hasNext()){
                Albaran alb=(Albaran) italb.next();
                q2=lpdPUEntityManager.createQuery("SELECT a FROM Albaran a, AlbaranFactura af WHERE a.iDalbaran=af.albaranFacturaPK.iDalbaran AND a.iDalbaran="+alb.getIDalbaran());
                List alb2=q2.getResultList();
                if(alb2.isEmpty()){
                    albaranesCliente.add(alb);
                }
            }
            if(!albaranesCliente.isEmpty()){
                this.Facturar();
            }

       }
        if(albaranesCliente.isEmpty()){

                JOptionPane.showMessageDialog(this, "No hay albaranes para facturar");

        }
    }//GEN-LAST:event_facturarTodo

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CrearFactura().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<gestion.AlbaranFactura> albaranFacturaList;
    private javax.persistence.Query albaranFacturaQuery;
    private java.util.List<gestion.Albaran> albaranList;
    private javax.persistence.Query albaranQuery;
    private java.util.List<clientes.Cliente> clienteList;
    private javax.persistence.Query clienteQuery;
    private java.util.List<gestion.Factura> facturaList;
    private java.util.List<gestion.Factura> facturaList1;
    private javax.persistence.Query facturaQuery;
    private javax.persistence.Query facturaQuery1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.persistence.EntityManager lpdPUEntityManager;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables



}
